package com.agriculture.competition.service.impl;

import com.agriculture.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
@Slf4j
public class DownloadFile {

//    public static InputStream getInputStream(String fileURL) {
//        InputStream inputStream = null;
//        try {
//            // 创建一个URL对象
//            URL url = new URL(fileURL);
//            // 打开一个连接
//            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//            // 设置请求方法为GET
//            // httpConn.setRequestMethod("GET");
//            // 获取响应码
//            int responseCode = httpConn.getResponseCode();
//            log.info("DownloadFile.getInputStream====responseCode:" + responseCode);
//            // 如果响应码是HTTP_OK（200），则继续
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                // 获取输入流（文件流）
//                inputStream = new BufferedInputStream(httpConn.getInputStream());
//            }
//            // 断开连接
//        } catch (Exception e) {
//            log.error("DownloadFile.getInputStream:", e);
//        }
//        log.info("DownloadFile.getInputStream====result:" + inputStream);
//        return inputStream;
//    }


    public static InputStream openConnectionAndGetInputStream(String fileUrl) throws IOException {
        HttpURLConnection httpConn = null;
        try {
            log.info("openConnectionAndGetInputStream==开始" + fileUrl);
            if (StringUtils.isNotBlank(fileUrl)) {
                String fileUrlNew = fileUrl.replaceAll("https://0ac42e3fb9ddaf49.vac.jlau.edu.cn/", "http://127.0.0.1:9000/");
                URL url = new URL(fileUrlNew);
                log.info("openConnectionAndGetInputStream===fileUrlNew:"+fileUrlNew);
                httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(5000); // 设置连接超时时间
                httpConn.setReadTimeout(5000); // 设置读取超时时间
                // 检查响应码是否为 200 (HTTP_OK)
                int responseCode = httpConn.getResponseCode();
                log.info("openConnectionAndGetInputStream==responseCode" + responseCode);
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    throw new IOException("HTTP 请求失败，响应码: " + responseCode);
                }
            }
        } catch (IOException e) {
            log.error("DownloadFile.openConnectionAndGetInputStream:", e);
        }
        log.info("openConnectionAndGetInputStream==InputStream" + httpConn.getInputStream());
        return httpConn.getInputStream();
    }
}